from django.shortcuts import render
import os, django
# 配置其他py文件正常使用djangoORM
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_orm.settings")
django.setup()
# Create your views here.

from connect_db.models import User
from django.http import HttpResponse, JsonResponse
from django.db.models import Sum
import json
from connect_db.models import Category, UseTime, SubjectCategory
import datetime


# def api_interface(request):
#     if request.method == "GET":
#         result = {}
#         cat = Category.objects.all()
#         for i in cat:
#             result[str(i)] = str(i)
#         return JsonResponse(result)
#
#


def time_frequency(category="汤家凤数学基础"):
    time = [i + j / 10 for i in range(6, 24) for j in range(10)]
    frequency = [0] * len(time)

    user = User.objects.get(id=1)
    category = Category.objects.get(category=category)
    data = UseTime.objects.filter(user=user, category=category)
    for i in data:
        start = float(i.start_time.strftime("%H")) + round(float(i.start_time.strftime("%M")) / 60, 1)
        stop = float(i.stop_time.strftime("%H")) + round(float(i.stop_time.strftime("%M")) / 60, 1)
        for j in range(time.index(start), time.index(stop)+1):
            frequency[j] += 1

    return time, frequency


def average_time_per_class():
    # 平均种学科的时间
    result = {}
    use_day = UseTime.objects.all().order_by("start_time")[0]
    subject_ues_time = UseTime.objects.values('category__subject_category__subject').annotate(s=Sum('use_time')).values(
        "category__subject_category__subject", 's').order_by("-s")
    for i in subject_ues_time:
        average_time = i['s'] / (datetime.datetime.now() - use_day.start_time).days
        result[i['category__subject_category__subject']] = {"all_time": i['s'], "average_time": average_time}
    return result


def today_distribute_time(category=None):
    if category is None:
        today_datas = UseTime.objects.filter(start_time__gte=datetime.datetime.now().strftime("%Y-%m-%d"))
    else:
        today_datas = UseTime.objects.filter(category=category, start_time__gte=datetime.datetime.now().strftime("%Y-%m-%d"))
    format_data = dict()
    format_data["use"] = list()
    format_data["time"] = list()

    format_data["use"].append(0)
    format_data["time"].append(6)

    total_use = 0

    for today_data in today_datas:
        format_data["time"].append(
            float(today_data.start_time.strftime("%H")) + float(today_data.start_time.strftime("%M")) / 60 - 0.0001)
        format_data['use'].append(0)

        format_data["time"].append(float(today_data.start_time.strftime("%H")) + float(today_data.start_time.strftime("%M")) / 60)
        format_data['use'].append(1)
        format_data["time"].append(float(today_data.stop_time.strftime("%H")) + float(today_data.stop_time.strftime("%M")) / 60)
        format_data['use'].append(1)
        format_data["time"].append(
            float(today_data.stop_time.strftime("%H")) + float(today_data.stop_time.strftime("%M")) / 60 - 0.0001)
        format_data['use'].append(0)
        total_use += today_data.use_time

    format_data["use"].append(0)
    format_data["time"].append(22)
    format_data["total_use"] = total_use

    return format_data


def today_distribute_time_classify_by_category():
    today_categorys = UseTime.objects.filter(start_time__gte=datetime.datetime.now().strftime("%Y-%m-%d")).values(
        "category").distinct()
    result = {}
    for i in today_categorys:
        result[Category.objects.get(id=i["category"]).category] = today_distribute_time(i["category"])
    return result


def detail_of_all_data():
    last_week_data = UseTime.objects.filter(start_time__gte=datetime.datetime.now()-datetime.timedelta(weeks=1)).values(
        "start_time__day").annotate(sum=Sum('use_time')).values_list('start_time__day', 'sum')

    last_month_data = UseTime.objects.filter(
        start_time__gte=datetime.datetime.now() - datetime.timedelta(days=30)).values(
        "start_time__day").annotate(sum=Sum('use_time')).values_list('start_time__day', 'sum')

    # 每一号数据
    every_day_of_month = UseTime.objects.filter().values(
        "start_time__day").annotate(sum=Sum('use_time')).values_list('start_time__day', 'sum')

    every_week = UseTime.objects.values(
        "start_time__week").annotate(sum=Sum('use_time')).values_list('start_time__week', 'sum')

    every_month = UseTime.objects.values(
        "start_time__month").annotate(sum=Sum('use_time')).values_list('start_time__month', 'sum')

    return {
        "every_day_of_month": ([i[0] for i in every_day_of_month], [i[1] for i in every_day_of_month]),
        "every_week": ([i[0] for i in every_week], [i[1] for i in every_week]),
        "last_week_data": ([str(i[0]) for i in last_week_data], [i[1] for i in last_week_data]),
        "last_month_data": ([i[0] for i in last_month_data], [i[1] for i in last_month_data]),
        "every_month": ([i[0] for i in every_month], [i[1] for i in every_month])
    }


if __name__ == '__main__':
    today_datas = UseTime.objects.values(
        "start_time__month").annotate(sum=Sum('use_time')).values_list('start_time__month', 'sum')
    print(today_datas)
